package com.sky.service.Impl;

import cn.hutool.core.collection.CollStreamUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.controller.WebSocketServer;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.MapUtil;
import com.sky.utils.WeChatPayUtil2;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WeChatPayUtil2 weChatPayUtil;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShopingMapper shopingMapper;

    @Autowired
    private MapUtil mapUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    //    取消订单
    @Override
    public void admincancel(OrdersCancelDTO dto) {
        Orders o = new Orders();
        BeanUtils.copyProperties(dto,o);
        o.setStatus(Orders.CANCELLED);
        orderMapper.updateOrder(o);
    }

    //    各个状态的订单数量统计
    @Override
    public OrderStatisticsVO selectByStatus() {
        Integer s2 = orderMapper.selectByStatus(Orders.TO_BE_CONFIRMED);
        Integer s3 = orderMapper.selectByStatus(Orders.CONFIRMED);
        Integer s4 = orderMapper.selectByStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO o = new OrderStatisticsVO();
        o.setToBeConfirmed(s2);
        o.setConfirmed(s3);
        o.setDeliveryInProgress(s4);

        return o;
    }


//    完成订单
    @Override
    public void complete(Long id) {
        Orders o = new Orders();
        o.setId(id);
        o.setStatus(Orders.COMPLETED);
        o.setDeliveryTime(LocalDateTime.now());
        orderMapper.updateOrder(o);
    }

//    拒单
    @Override
    public void rejection(OrdersRejectionDTO dto) {
        Orders o = new Orders();
        BeanUtils.copyProperties(dto,o);
        o.setStatus(Orders.CANCELLED);
        orderMapper.updateOrder(o);
    }

//    接单
    @Override
    public void updateConfirm(OrdersConfirmDTO dto){
        Orders o = new Orders();
        BeanUtils.copyProperties(dto,o);
        o.setStatus(Orders.CONFIRMED);
        orderMapper.updateOrder(o);

    }


//    查询订单详情
    @Override
    public OrderVO selectWithDetail(Long id){
        OrderVO orderVO = orderMapper.selectById(id);
        List<OrderDetail> orderDetail = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetail);
        return orderVO;
    }



//    派送订单
    @Override
    public void delivery(Long id) {
        Orders o = new Orders();
        o.setId(id);
        o.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.updateOrder(o);
    }


//    订单搜索
    @Override
    public PageResult page(OrdersPageQueryDTO dto) {

        // 设置分页
        PageHelper.startPage(dto.getPage(), dto.getPageSize());

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(dto.getStatus());

        // 分页条件查询
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                //添加菜品名
                ArrayList a = new ArrayList();
                for (OrderDetail o : orderDetails) {
                    a.add(o.getName());
                }
                orderVO.setOrderDishes(a.toString());

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }



//================================================= 以下为用户端  ===============================================

//    催单
    @Override
    public void reminder(Long id) {

        OrderVO o = orderMapper.selectById(id);
        Map map = new HashMap();
        map.put("type",2);//添加数据类型,1表示来单提示
        map.put("orderId",o.getId());
    //        添加订单号
        map.put("content","订单号"+o.getNumber());
    //        推向浏览器
        webSocketServer.send2Client(JSONObject.toJSONString(map));
    }

//    再来一单
    @Override
    @Transactional
    public void repetition(Long id) {
        Long userid = BaseContext.getCurrentId();
        //根据订单id查询订单信息
        List<OrderDetail> orderDetails =orderDetailMapper.selectByOrderId(id);

        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetails) {
            //构建购物车
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            // 购物车信息从之前的订单明细中复制
            shoppingCart.setUserId(userid);
            //为新的购物车赋值用广d和创律时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartList.add(shoppingCart);
        }
        shopingMapper.insertBatch(shoppingCartList);
    }

//    历史订单查询
    @Override
    public PageResult userpage(OrdersPageQueryDTO DTO){
        DTO.setUserId(BaseContext.getCurrentId());
        // 设置分页参数
        Page<Orders> page = orderMapper.pageQuery(DTO);

        List<OrderVO> list = new ArrayList();
        // 查面订单明细，并且封装
        List<Orders> result = page.getResult();
        //获取分页查询到的所有订单id
        Set<Long> orderIds = result.stream().map(Orders::getId).collect(Collectors.toSet());// 通过多个订单id查询相应的订单明细信息
        List<OrderDetail> orderDetaillist = orderDetailMapper.getHistoryOrders(orderIds);
        // 根据订单id进行分组 map<订单id，订单明细集合>
        Map<Long, List<OrderDetail>> orderDetailMap = CollStreamUtil.groupByKey(orderDetaillist, OrderDetail::getOrderId);
        result.stream().forEach(Orders ->{
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(Orders, orderVO);
            List<OrderDetail> orderDetails = orderDetailMap.get(Orders.getId());
            orderVO.setOrderDetailList(orderDetails);
            list.add(orderVO);
        });

        return new PageResult(page.getTotal(),list);
    }

//    取消订单
    @Override
    public void cancel(Long id) throws Exception {
        OrderVO orderVO = orderMapper.selectById(id);
        Orders s = new Orders();
        BeanUtils.copyProperties(orderVO,s);
        if (orderVO == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        if(orderVO.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        if(orderVO.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            weChatPayUtil.refund(orderVO.getNumber(),orderVO.getNumber(),new BigDecimal(0.01),new BigDecimal(0.01));
        }

        s.setStatus(Orders.CANCELLED);
        s.setCancelTime(LocalDateTime.now());
        s.setCancelReason("用户取消");
        orderMapper.cancel(s);
    }

//    查询订单详情
    @Override
    public OrderVO seleteOrderAll(Long id) {
        OrderVO orderVO = orderMapper.selectById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.selectByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

//    用户下单
    @Override
    @Transactional
    public OrderSubmitVO Order(OrdersSubmitDTO dto){
        //异常情况的处理（收货地址为空、超出配送范围、购物车为空）
        AddressBook addressBook = addressBookMapper.seleteById(dto.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        //  超出配送范围判断
        Boolean checkResult = mapUtil.checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        if (!checkResult) {
            throw new OrderBusinessException("超出确认范围");
        }

        //查询当前用户的购物车数据
        List<ShoppingCart> shoppingCartList = shopingMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(dto,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());

        //向订单表插入1条数据
        orderMapper.InsertOrder(order);

        //订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }

        //向明细表插入n条数据
        orderDetailMapper.insertBatch(orderDetailList);

        //清理购物车中的数据
        shopingMapper.deleteByUserId(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();

        return orderSubmitVO;

    }

    /**
     * 订单支付
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        Map map = new HashMap();
        map.put("type",1);//添加数据类型,1表示来单提示
        map.put("orderId",orders.getId());
//        添加订单号
        map.put("content","订单号"+outTradeNo);
//        推向浏览器
        webSocketServer.send2Client(JSONObject.toJSONString(map));

        orderMapper.update(orders);
    }


}
